﻿using Devonline.AspNetCore;
using Devonline.Communication.Client;
using Devonline.Core;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;

var builder = WebApplication.CreateBuilder(args);
var appSetting = builder.UseAppSetting<ClientSetting>();
if (appSetting == null)
{
    throw new Exception("缺少必要的基础配置项");
}

builder.Host.UseSerilog((context, logger) => logger.ReadFrom.Configuration(context.Configuration));

var services = builder.Services;
services.AddLogging();
services.AddSingleton<MessageClient>();

var app = builder.Build();
await app.StartAsync();

var logger = app.Services.GetService<ILogger<Program>>();
var client = app.Services.GetService<MessageClient>();
if (client != null)
{
    client.OnReceive<string>(message => logger.LogInformation("Yes, I receive the {messageType} message: {content} from {sender} at {receiveTime}!", message.Type, message.Content, message.Sender, message.ReceiveTime));
    client.OnAck<string>(messageId => logger.LogInformation("Yes, I receive the ACK message {messageId} from {receiver}!", messageId, appSetting.Receiver));

    try
    {
        await client.StartAsync();

        var input = Console.ReadLine();
        while (input != "exit")
        {
            //var message = new Message { Content = input, Receiver = appSetting.Receiver };
            //await client.SendAsync(message);
            await client.SendAsync(input);
            input = Console.ReadLine();
        }

        await client.StopAsync();
    }
    catch (Exception ex)
    {
        logger.LogError(ex, $"客户端链接出错, {ex.GetMessage()}!");
    }

    await app.StopAsync();
    logger.LogInformation("客户端退出, 消息中心连接结束!");
}